package com.sky.service.redis.impl;

import com.sky.dto.CourierTradeQueryDto;
import com.sky.dto.UserLoginDTO;
import com.sky.exception.CodeExpiredException;
import com.sky.exception.CourierNotExistException;
import com.sky.exception.ParameterIsNullException;
import com.sky.mapper.common.ShortUrlMapper;
import com.sky.mapper.redis.CourierTradeOrderMapper;
import com.sky.mapper.redis.RedisCourierMapper;
import com.sky.mapper.user.OrderMapper;
import com.sky.pojo.Courier;
import com.sky.pojo.CourierTradeOrder;
import com.sky.pojo.Orders;
import com.sky.pojo.ShotUri;
import com.sky.result.Result;
import com.sky.service.redis.RedisCourierService;
import com.sky.utils.ShortUrlGenerator1;
import com.sky.vo.CourierTradeOrderVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class RedisCourierServiceImpl implements RedisCourierService {
    @Resource
    private RedisCourierMapper redisCourierMapper;
    @Resource
    private CourierTradeOrderMapper courierTradeOrderMapper;
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private OrderMapper orderMapper;
    /**
     * 配送员登录
     * */
    @Override
    public Result login(UserLoginDTO dto) {
        //判断dto是否为空
        if (dto==null){
            throw new ParameterIsNullException("缺少请求参数");
        }
        //获取验证码
        String key="code:"+dto.getTelephone();
        String serverCode = (String) redisTemplate.opsForValue().get(key);
        //判断验证码是否为空
        if (serverCode==null){
            throw new CodeExpiredException("验证码已过期,请重新发送");
        }
        //校验验证码
        if (!serverCode.equals(dto.getCode())){
            throw new CodeExpiredException("验证码错误");
        }
        //获取配送员的信息，返回给前端
        Courier courier = redisCourierMapper.getCourierByTelephone(dto.getTelephone());
        if (courier==null){
            throw new CourierNotExistException("配送员的电话号码不存在");
        }
        return Result.success(courier);
    }
    /**
     * 骑手已接单
     * */
    @Override
    public void reveivingOrder(Long courierId, Long tradeNo) {
        //判断courierId和tradeNo是否为空
        if (courierId==null||tradeNo==null){
            throw new ParameterIsNullException("缺少请求参数");
        }
        //判断运单是否为空
        CourierTradeOrder courierTradeOrder = courierTradeOrderMapper.queryTradeOrderByTradeNo(tradeNo);
        if (courierTradeOrder==null){
            throw new CourierNotExistException("运单不存在");
        }
        //修改运单的状态为已接单
        courierTradeOrderMapper.updateCourierStuatus(tradeNo,CourierTradeOrder.DELIVORING);
        //System.out.println("影响数据条数"+row);
        //修改订单状态为接单状态
        //System.out.println("订单号"+courierTradeOrder.getOrderNumber());
        orderMapper.updateStatusByNumber(courierTradeOrder.getOrderNumber(), Orders.TOBEPICKEDUP);
        //System.out.println("影响数据条数"+row1);
        //删除redis的缓存数据
        String key = "courier_trade_order_"+courierId+"_"+CourierTradeOrder.DISPATCH_OK;
        redisTemplate.delete(key);
        //通知用户骑手已接单
        //        3.发送短信给用户，并且附带地址，用户点击可以查看骑手和用户的位置
        // alismsTemplate.sendMessage(tradeOrder.getOrderNumber(),"4477");
        sendMessageToCustomer(courierTradeOrder);
    }
    /**
     * 根据骑手的id查询骑手的信息
     * */
    @Override
    public Result<Courier> findById(Long courierId) {
        return redisCourierMapper.findById(courierId);
    }

    @Autowired
    private ShortUrlGenerator1 shortUrlGenerator;

    @Autowired
    private ShortUrlMapper shortUrlMapper;
    private void sendMessageToCustomer(CourierTradeOrder tradeOrder) {
        String code = "";
        while (true){
            long index = 0L;
            code = shortUrlGenerator.creatKey();
            int hashCode = code.hashCode();
            if(hashCode<0){
                index = Math.abs(hashCode)+ 2147483648L;
            }else{
                index = hashCode;
            }
            //判断bit位是否存在
            Boolean res = redisTemplate.opsForValue().getBit("short_code", index);
            if(!res){
                //生成成功，将bit位置为存在
                redisTemplate.opsForValue().setBit("short_code",index,true);
                break;
            }
        }
        //2.拼接短链
        String shortUrl = shortUrlGenerator.getShortUrl(code);

        //2.生成fullUrl
        String fullUrl = shortUrlGenerator.getFullUrl(tradeOrder.getTradeNo(),
                tradeOrder.getCourierId(),
                tradeOrder.getCustomerExpectedDeliveryTime());
        //3.保存入库发送短信
        ShotUri shortUrlPojo = ShotUri.builder()
                .shotUrl(shortUrl)
                .fullUrl(fullUrl)
                .expireTime(tradeOrder.getCustomerExpectedDeliveryTime())
                .shotCode(code)
                .tradeNo(tradeOrder.getTradeNo())
                .build();
        shortUrlMapper.save(shortUrlPojo);
        System.out.println("--------发送短信通知用户:"+shortUrl);
    }
}
